package com.test;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一个线程打印1～52,另一个线程打印A～Z,打印顺序应该是12A34B56C…5152Z。
 */
public class ThreadTest03 {
    private static volatile int i = 1;
    private static volatile char c = 65;//A
    Object obj = new Object();
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();
    static volatile boolean shouldStop = false;

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    ThreadTest03.method12();

                }
            }).start();

            Thread.sleep(500);

            new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    ThreadTest03.methodA();
                }
            }).start();
        }
    }

    public static void method12() {
        lock.lock();
        try {
            int sum = 0;
            while (!shouldStop) {
                System.out.println(Thread.currentThread().getName() + "_" + i);
//                Thread.sleep(500);
                i++;
                sum++;
                if (sum % 2 == 0) {
                    condition.signal();
                    condition.await();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void methodA() {
        lock.lock();
        try {
            while (!shouldStop) {
                System.out.println(Thread.currentThread().getName() + "_" + c);
//                Thread.sleep(500);
                if (c >= 90) {//等于Z的时候就该停手了
                    shouldStop = true;// 告知thread-0线程,是时候停止了
                }
                c++;
                condition.signal();
                condition.await();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
